import cv2 as cv
import numpy as np

img = cv.imread('../pic/sudoku.png')
cv.imshow('img', img)
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
edges = cv.Canny(gray, 50, 150, apertureSize=3)
lines = cv.HoughLines(edges, rho=1, theta=np.pi / 180, threshold=200)

for line in lines:
    # 获取霍夫变换返回的 rho 和 theta 值
    rho, theta = line[0]
    # 计算 theta 的余弦和正弦，分别得到 a 和 b
    a = np.cos(theta)
    b = np.sin(theta)
    # 直线上离原点最近的点的坐标 (x0, y0)
    x0 = a * rho
    y0 = b * rho
    # 这两个端点 (x1, y1) 和 (x2, y2) 就是在图像上绘制直线的两个端点
    # 从离原点最近的点出发，沿着直线的两个方向各延伸 1000 像素来计算这两个端点
    x1 = int(x0 + 1000 * (-b))
    y1 = int(y0 + 1000 * (a))
    x2 = int(x0 - 1000 * (-b))
    y2 = int(y0 - 1000 * (a))
    cv.line(img, (x1, y1), (x2, y2), (0, 0, 255), 2)

cv.imshow('houghlines3', img)
cv.waitKey()
cv.destroyAllWindows()
